# -*- coding: utf-8 -*-
# filename: main.py
import web
import json
from handle import Handle
import linksql
import weiyi
import logging

urls = (
    '/wx', 'Handle',
    '/', 'index',
    '/alipay', 'alipay',
    '/tixian', 'tixian',
    '/userinfo', 'userinfo',
    '/getorderplus','getorderplus'
)
if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO,format = '%(asctime)s - %(filename)s:%(lineno)s - %(levelname)s - %(message)s',filename = 'budeniaolog.log')
    app = web.application(urls, globals())
    app.run()


class querycoupon:
    def POST(self):
        webinput = web.data()
        json_webinput = json.loads(webinput)
        topcate = json_webinput['query']['topcate']
        subcate = json_webinput['query']['subcate']
        page = json_webinput['query']['PageIndex']
        pagesize = json_webinput['query']['PageSize']
        res = weiyi.products(topcate, subcate, page, pagesize)
        json_res = {"Result":"请求成功", "Quans":res['data']}
        return json.dumps(json_res)

class index:
    def GET(self):
        render = web.template.render('templates')
        webinput = web.input(openid=None)
        if not(webinput.openid):
            return "the budeniao is running!"
        else:
            return render.index(webinput.openid)

class userinfo: #用户信息接口
    def GET(self):
        webinput = web.input(openid = 'o1mDH1HT8Nf7EdDc2-WJbw8mXkvk')
        sqldata = linksql.app_userinfo(webinput.openid)
        jsondata = json.dumps(sqldata)
        return jsondata

class getorderplus: #订单查询接口
    def GET(self):
        webinput = web.input(trade_id=None)
        if webinput.trade_id:
            sqldata = linksql.getOrderPlus(webinput.trade_id)
            jsondata = json.dumps(sqldata)
            return jsondata
        else:
            return None

class alipay:#支付宝绑定
    def GET(self):
        webinput = web.input(zhifubao=None, xingming=None, openid=None)
        render = web.template.render('templates')
        if isphone(webinput.zhifubao) and webinput.xingming and webinput.openid: 
            sqldata = linksql.alipay(webinput.zhifubao, webinput.xingming, webinput.openid)
            if sqldata:
                return render.msg("绑定成功，请在公众号重新发起提现")
            else:
                return render.msg("绑定失败，请输入正常的用户信息")
        else:
            return False

class tixian:
    def GET(self):
        render = web.template.render('templates')
        openid = web.input(openid=None).openid
        return render.msg(linksql.cash(openid)['msg'])

def isphone(number):
    phoneprefix=['130','131','132','133','134','135','136','137','138','139','150','151','152','153','156','158','159','170','183','182','185','186','188','189']
    if not(number):
        return False
    if len(number) != 11:
        return False
    if  not(number.isdigit()):
        return False
    if number[:3] in phoneprefix:
         return True
    else:
         return False
